package com.rbmh.network.utils;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class GitCommitToExcel {
    private static final String GIT_LOG_FILE = "C:\\Users\\Administrator\\Desktop\\git_log.txt";
    private static String EXCEL_FILE = "C:\\Users\\Administrator\\Desktop\\";

    /**
     * git 数据收集：  git log --since="2024-06-19" --until="2024-06-27" --pretty=format:"phis|%an|%cd|%s" --date=format:'%Y-%m-%d %H:%M:%s' > c:/commits.txt
     * @param args
     */
    public static void main(String[] args) {
        // 从文件中读取 Git 提交记录
        String gitLog = readGitLogFromFile();

        // 解析提交记录并转换为 Excel 数据
        List<String[]> excelData = parseGitLog(gitLog);

        // 写入 Excel 文件
        EXCEL_FILE = EXCEL_FILE + System.currentTimeMillis() + "-commits.xlsx";
        writeToExcel(excelData, EXCEL_FILE);
        System.out.println("文件已经生成："+EXCEL_FILE);
    }

    private static String readGitLogFromFile() {
        return cn.hutool.core.io.FileUtil.readString(GIT_LOG_FILE, "UTF-8");
    }

    private static List<String[]> parseGitLog(String gitLog) {
        List<String[]> excelData = new ArrayList<>();
        String[] lines = gitLog.split("\n");
        for (String line : lines) {
            String[] fields = line.split("\\|");
            excelData.add(fields);
        }
        return excelData;
    }

    private static void writeToExcel(List<String[]> excelData, String fileName) {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("Commits");

            // 添加标题行
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("模块");
            headerRow.createCell(1).setCellValue("姓名");
            headerRow.createCell(2).setCellValue("时间");
            headerRow.createCell(3).setCellValue("备注");

            int rowNum = 1;
            for (String[] row : excelData) {
                Row excelRow = sheet.createRow(rowNum++);
                int cellNum = 0;
                for (String cell : row) {
                    excelRow.createCell(cellNum++).setCellValue(cell);
                }
            }
            try (FileOutputStream outputStream = new FileOutputStream(fileName)) {
                workbook.write(outputStream);
            }
            System.out.println("Excel file created: " + fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}